<template>
  <j-modal
    title="AI仿生助理"
    :width="900"
    switchFullscreen
    :fullscreen="false"
    :draggable="true"
    :okButtonProps="{ class: { 'jee-hidden': true } }"
    @cancel="handleCancel"
    :cancelButtonProps="{ class: { 'jee-hidden': true } }"
    :visible="aiVisible"
    :body-style="{ padding: '0px' }"
    class="ai-fszl-modal"
    centered
  >
    <div class="main">
      <a-row>
        <a-col :span="5">
          <div class="chat-container">
            <a-card
              class="box-card"
              :body-style="{ padding: '0px' }"
              :bordered="false"
              :head-style="{ height: '0px' }"
              title=""
            >
              <div :class="['beWsfr_U', activeType == 1 ? 'active' : '']" @click="selectItem(1)">
                <div class="P9ZK1OTT">
                  <div class="j88GOXPF j88GOXPF-1"></div>
                  <div class="NvHLoWu8">算法分析助理</div>
                </div>
              </div>

              <div :class="['beWsfr_U', activeType == 2 ? 'active' : '']" @click="selectItem(2)">
                <div class="P9ZK1OTT">
                  <div class="j88GOXPF"></div>
                  <div class="NvHLoWu8">智能日报助理</div>
                </div>
              </div>
            </a-card>
          </div>
        </a-col>
        <a-col :span="19">
          <div class="chat-container">
            <a-card
              :title="getTitle"
              class="box-card"
              :head-style="{ background: '#333333', color: '#ccc', fontWeight: 'bold' }"
              :body-style="{ background: '#4b4b4b' }"
              :bordered="false"
            >
              <div ref="chatContainer" class="chat-messages">
                <div v-if="isCover">
                  <div class="nlux-comp-avatarPicture"></div>

                  <div class="nlux-comp-welcomeMessage-personaName">您好，我是中孚AI助手</div>
                  <div class="nlux-comp-welcomeMessage-text">您可以尝试点击下方的快捷入口开启体验</div>
                  <template v-if="activeType == 1">
                    <a-tag
                      v-for="item in tags"
                      style="
                        font-size: 16px;
                        letter-spacing: 2px;
                        padding: 5px 9px;
                        color: #c78b4c;
                        background: #333;
                        border-color: #7c562f;
                        cursor: pointer;
                        margin-top: 10px;
                      "
                      :key="item.text"
                      @click="tagClick(item.text)"
                      >{{ item.text }}</a-tag
                    >
                  </template>
                  <template v-else>
                    <a-tag
                      style="
                        font-size: 16px;
                        letter-spacing: 2px;
                        padding: 5px 9px;
                        color: #c78b4c;
                        background: #333;
                        border-color: #7c562f;
                        cursor: pointer;
                        margin-top: 10px;
                      "
                      v-for="item in tags2"
                      :key="item.text"
                      @click="tagClick(item.text)"
                      >{{ item.text }}</a-tag
                    >
                  </template>
                </div>
                <template v-else>
                  <div
                    v-for="message in messages"
                    :key="message.id"
                    class="message"
                    :class="{ 'from-me': message.fromMe }"
                  >
                    <div :class="['avatar', activeType == 1 ? 'avatar-1' : 'avatar-2']" v-if="!message.fromMe"></div>
                    <div class="avatar-me" v-else>
                      {{ message.from }}
                    </div>
                    <div class="content" :class="{ content1: !message.fromMe }">
                      <!-- {{ message.content }} -->
                      <div class="main" style="padding-left: 10px">
                        <vue-markdown
                          :source="message.content"
                          :breaks="true"
                          :typographer="true"
                          :linkify="true"
                          :highlight="false"
                        ></vue-markdown>
                        <a-spin v-if="message.content == '努力思索中，请耐心等待...'">
                          <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
                        </a-spin>
                      </div>
                    </div>
                  </div>
                </template>
              </div>
              <div class="chat-input">
                <a-input
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 8 }"
                  v-model="newMessage"
                  @keyup.enter.native="sendMessage"
                  placeholder="请输入您想查询的信息..."
                  style="margin-right: 10px; background-color: #333333; color: #ccc; border-color: #656565"
                />
                <div style="width: 100px">
                  <a-dropdown-button @click="sendMessage" type="primary">
                    发 送
                    <a-menu slot="overlay" @click="handleMenuClick">
                      <a-menu-item key="1" @click="audioCHangeWord">
                        <a-tooltip placement="topLeft" title="点击语音识别后，说出您的需求" arrow-point-at-center>
                          <a-icon type="audio" /><span v-if="isListening">语音识别中...</span
                          ><span v-else>语音识别</span>
                        </a-tooltip>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown-button>
                  <!-- <a-button type="primary" @click="sendMessage" size="large" style="height: 58px; width: 97px"
                  >发 送</a-button
                >
                <a-button type="primary" @click="audioCHangeWord" icon="audio" size="small" style="margin-top: 6px">
                  <span v-if="isListening">语音识别中...</span><span v-else>语音识别</span>
                </a-button> -->
                  <!-- <a-checkbox v-model="isAuto" :checked="isAuto"> 自动发送 </a-checkbox> -->
                </div>
              </div>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>
  </j-modal>
</template>

<script>
// import MarkdownIt from "markdown-it";
import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'
import VueMarkdown from 'vue-markdown'
export default {
  components: {
    VueMarkdown,
  },
  data() {
    return {
      aiVisible: false,
      baseURL: 'http://120.46.139.139:8003',
      messages: [
        {
          id: 1,
          from: 'You',
          content: '您好，有什么需要我帮助的吗？',
          fromMe: false,
        },
      ],
      messages1: [
        // {
        //   id: 1,
        //   from: 'You',
        //   content: '您好，有什么需要我帮助的吗？',
        //   fromMe: false,
        // },
      ],
      messages2: [
        // {
        //   id: 1,
        //   from: 'You',
        //   content: '您好，有什么需要我帮助的吗？',
        //   fromMe: false,
        // },
      ],
      newMessage: '',
      resultMessage: '',
      newCode: '',
      access_token: '',
      accessCodeInput: '',
      dayLog: [],
      sessionId: null,
      isListening: false,
      activeType: 1,
      tags: [], //'2236号电解槽2023年6月3号的冷热指数是多少？','查询2023年6月3日2236号电解槽的日报数据，用表格显示','查询2023年6月3日2236号电解槽的工作电压','预测2236号电解槽三天的出铝量',
      tags2: [], //'2236号电解槽2023年6月平均值'
      isAuto: true,
      isCover: true, //封面
    }
  },
  created() {
    this.loadExamples('cxzl_examples')
    this.loadExamples('fxzl_examples')
  },
  methods: {
    show() {
      this.messages1 = []
      this.messages2 = []
      this.isCover = true
      this.aiVisible = true
    },
    handleCancel() {
      this.aiVisible = false
    },
    tagClick(value) {
      this.newMessage = value
      this.sendMessage()
    },
    getTitle() {
      if (this.activeType == 1) {
        this.messages = this.messages1
        return '算法分析助理'
      }
      if (this.activeType == 2) {
        this.messages = this.messages2
        return '智能日报助理'
      }
      return ''
    },
    selectItem(type) {
      if (this.activeType == type) {
        return
      }
      this.activeType = type
      this.newMessage = ''
      if (type == 1) {
        this.isCover = this.messages1.length == 0
        this.messages = this.messages1
      }
      if (type == 2) {
        this.isCover = this.messages2.length == 0
        this.messages = this.messages2
      }
    },
    sendMessage() {
      var that = this
      if (that.activeType == 1) {
        this.sendMessage1()
      }
      if (that.activeType == 2) {
        this.sendMessage2()
      }
    },
    sendMessage1() {
      var that = this
      if (!this.newMessage.trim()) {
        return
      }
      that.isCover = false
      const newId = this.messages.length + 1
      this.messages.push({
        id: newId,
        from: 'Me',
        content: this.newMessage,
        fromMe: true,
      })
      this.newMessage = ''
      const ask = this.messages[this.messages.length - 1].content
      const newResultId = newId + 1
      this.messages.push({
        id: newResultId,
        from: 'You',
        content: '努力思索中，请耐心等待...',
        fromMe: false,
      })
      //聊天框滚动效果
      const chatContainer = this.$refs.chatContainer
      this.$nextTick(() => {
        chatContainer.scrollTop = chatContainer.scrollHeight
      })

      // this.$http
      //   .post(
      //     this.baseURL + '/chat/dialogue',
      //     {
      //       prompt: ask,
      //       session_id: that.sessionId || undefined, // 避免传递 null
      //     },
      //     {
      //       headers: {
      //         'x-token': 'lyarc-eff11f4ca97069dcd1e35ffef6087197',
      //       },
      //     }
      //   )
      //   .then((res) => {
      //     // debugger
      //     // if (res.data.result === '访问密码错误,请重新输入') {
      //     //   this.messages[newId].content = '访问密码错误,请重新输入'
      //     //   return
      //     // }
      //     this.messages[newId].content = ''
      //     const lines = res.trim().split('\n')
      //     for (let line of lines) {
      //       if (line) {
      //         console.log(line)
      //         line = line.replace('data: ', '')
      //         console.log(line)
      //         const parsedLine = JSON.parse(line)
      //         if (parsedLine.text == null) {
      //           continue
      //         }
      //         //appendMessage(parsedLine.text, 'bot', botMessageId);\
      //         that.messages[newId].content += parsedLine.text
      //         if (!that.sessionId && parsedLine.session_id) {
      //           that.sessionId = parsedLine.session_id
      //         }
      //       }
      //     }
      //     this.messages1 = this.messages
      //     //this.messages[newId].content = md.render(that.messages[newId].content)
      //     //console.log(md.render(res.data.result));
      //     this.$nextTick(() => {
      //       chatContainer.scrollTop = chatContainer.scrollHeight
      //     })
      //   })
      var url = this.baseURL + '/chat/dialogue'
      this.send(ask, newId, url)
    },
    sendMessage2() {
      var that = this

      that.isCover = false
      const newId = this.messages.length + 1
      this.messages.push({
        id: newId,
        from: 'Me',
        content: this.newMessage,
        fromMe: true,
      })
      this.newMessage = ''
      const ask = this.messages[this.messages.length - 1].content
      const newResultId = newId + 1
      this.messages.push({
        id: newResultId,
        from: 'You',
        content: '努力思索中，请耐心等待...',
        fromMe: false,
      })
      //聊天框滚动效果
      const chatContainer = this.$refs.chatContainer
      this.$nextTick(() => {
        chatContainer.scrollTop = chatContainer.scrollHeight
      })
      var url = this.baseURL + '/assistant/dialogue'
      this.send(ask, newId, url)
      return
      this.$http
        .post(
          this.baseURL + '/assistant/dialogue',
          {
            prompt: ask,
            session_id: that.sessionId || undefined, // 避免传递 null
          },
          {
            headers: {
              'x-token': 'lyarc-eff11f4ca97069dcd1e35ffef6087197',
            },
          }
        )
        .then((res) => {
          // debugger
          // if (res.data.result === '访问密码错误,请重新输入') {
          //   this.messages[newId].content = '访问密码错误,请重新输入'
          //   return
          // }
          this.messages[newId].content = ''
          const lines = res.trim().split('\n')
          for (let line of lines) {
            if (line) {
              console.log(line)
              line = line.replace('data: ', '')
              console.log(line)
              const parsedLine = JSON.parse(line)
              if (parsedLine.text == null) {
                continue
              }
              //appendMessage(parsedLine.text, 'bot', botMessageId);\
              that.messages[newId].content += parsedLine.text
              if (!that.sessionId && parsedLine.session_id) {
                that.sessionId = parsedLine.session_id
              }
            }
          }
          this.messages2 = this.messages
          //this.messages[newId].content = md.render(that.messages[newId].content)
          //console.log(md.render(res.data.result));
          this.$nextTick(() => {
            chatContainer.scrollTop = chatContainer.scrollHeight
          })
        })
    },
    send(ask, newId, url) {
      var that = this
      const chatContainer = that.$refs.chatContainer
      var client = new XMLHttpRequest()
      client.open('POST', url)
      client.setRequestHeader('x-token', 'lyarc-eff11f4ca97069dcd1e35ffef6087197')
      client.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')

      let lastText = ''
      let currentText = ''

      client.onprogress = function (progressEvent) {
        currentText = progressEvent.target.responseText.replace(lastText, '')
        lastText = progressEvent.target.responseText

        try {
          const parsedLine = JSON.parse(currentText)
          if (parsedLine.text == null) {
            return
          }
          //appendMessage(parsedLine.text, 'bot', botMessageId);
          that.messages[newId].content = that.messages[newId].content.replace('努力思索中，请耐心等待...','')
          that.messages[newId].content += parsedLine.text
        } catch {}
        console.log('progressEvent.currentText', currentText)
        that.$nextTick(() => {
          chatContainer.scrollTop = chatContainer.scrollHeight
        })
      }
      client.onloadend = function (progressEvent) {
        console.log('END')
      }
      client.send(
        JSON.stringify({
          prompt: ask,
          session_id: that.sessionId || undefined, // 避免传递 null
        })
      )
    },
    audioCHangeWord() {
      var that = this
      that.newMessage = ''
      // 创建SpeechRecognition对象
      // eslint-disable-next-line no-undef
      var recognition = new webkitSpeechRecognition()
      console.log('recognition1', recognition)
      if (!recognition) {
        // eslint-disable-next-line no-undef
        recognition = new SpeechRecognition()
      }
      console.log('recognition2', recognition)
      console.log(11)
      // 设置语言
      recognition.lang = 'zh-CN'
      console.log(22)
      // 开始语音识别
      recognition.start()
      that.isListening = true
      console.log(33)
      // 监听识别结果
      recognition.onresult = function (event) {
        var result = event.results[0][0].transcript
        console.log('监听结果:', result)
        that.newMessage = result
      }

      // 监听错误事件
      recognition.onerror = function (event) {
        that.isListening = false
        that.$message('监听语音失败:' + event.error)
        console.error(event.error)
      }
      // 监听结束事件（包括识别成功、识别错误和用户停止）
      recognition.onend = function () {
        that.isListening = false
        console.log('语音识别停止')
        if (that.isAuto) {
          setTimeout(() => {
            that.sendMessage()
          }, 1500)
        }
      }
    },
    loadExamples(dictCode) {
      //优先从缓存中读取字典配置
      if (getDictItemsFromCache(dictCode)) {
        if ('fxzl_examples' == dictCode) {
          this.tags2 = getDictItemsFromCache(dictCode)
        }
        if ('cxzl_examples' == dictCode) {
          this.tags = getDictItemsFromCache(dictCode)
        }
      }
      //根据字典Code, 初始化字典数组
      ajaxGetDictItems(dictCode, null).then((res) => {
        if (res.success) {
          if ('fxzl_examples' == dictCode) {
            this.tags2 = res.result
          }
          if ('cxzl_examples' == dictCode) {
            this.tags = res.result
          }
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
.ai-fszl-modal {
  /deep/.ant-modal-content {
    background: transparent;
  }

  /deep/.ant-modal-header,
  .ant-card,
  .ant-card-body {
    background-color: rgba(255, 255, 255, 0.2); /* 半透明背景 */
    backdrop-filter: blur(20px); /* 背景模糊 */
    -webkit-backdrop-filter: blur(10px); /* 兼容老版本 Safari */
    color: #ddd;
    border-bottom: 0px;
  }

  /deep/.ant-modal-title,
  /deep/.ant-modal-close {
    color: #ccc;
  }

  /deep/.ant-modal-body {
    // background: #333333;
    background-color: rgba(255, 255, 255, 0.2); /* 半透明背景 */
    backdrop-filter: blur(20px); /* 背景模糊 */
    -webkit-backdrop-filter: blur(10px); /* 兼容老版本 Safari */
    color: #ddd;
    border-bottom: 0px;
  }
  .j-super-query-history-card {
    /deep/ .ant-card-body,
    /deep/ .ant-card-head-title {
      padding: 0;
    }

    /deep/ .ant-card-head {
      padding: 4px 8px;
      min-height: initial;
      background: red;
    }
  }
  /deep/.ant-card-bordered {
    border-color: #747474;
  }
  /deep/.ant-modal-footer {
    border: none;
  }
}

/deep/.el-dialog {
  width: 40%;
}
@media screen and (max-width: 700px) {
  /deep/.el-dialog {
    width: 80%;
  }
}
.chat-container {
  box-sizing: border-box;
  width: 100%;
  background: rebeccapurple;
  .box-card {
    /deep/.ant-modal-header {
      background: #333333;
      border-bottom: 1px solid #666565;
    }
  }
}
.chat-messages {
  height: 500px;
  overflow-y: auto;
}

.message {
  display: flex;
  align-items: center;
  margin: 10px;
}

.from-me {
  flex-direction: row-reverse;
}

.avatar {
  min-width: 40px;
  height: 40px;
  background-repeat: repeat-x;
  background-size: cover;
  border-radius: 5%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #fff;
}
.avatar-1 {
  background-image: url('../../../assets/icon-select.png');
}
.avatar-2 {
  //background: linear-gradient(322deg, #1f6ff5 7.93%, #9a7ffc 92.22%);
  background-image: url('../../../assets/icon-assay.png');
}
.avatar-me {
  min-width: 40px;
  height: 40px;
  background-color: #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #fff;
}

.content {
  font-size: 15px;
  letter-spacing: 2px;
  word-spacing: -2px;
  margin: 10px;
  padding: 15px 15px 0px 15px;
  border-radius: 5px;
  background-color: #95ec69;
  color: #000;
  text-align: left;
}
.content1 {
  background-color: #333333;
  color: #fff;
  letter-spacing: 2px;
  word-spacing: -2px;
  font-size: 15px;
}
.main {
  /deep/table {
    border-collapse: collapse;
    margin: 6px;
  }
  /deep/th,
  /deep/td {
    padding: 6px;
    text-align: center;
    border: 1px solid #545555;
  }
}
.chat-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0px 6px;
}
.beWsfr_U {
  align-items: center;
  cursor: pointer;
  display: inline-flex;
  height: 52px;
  justify-content: space-between;
  height: 56px;
  width: 100%;
  background: #3f4141;
  color: #b1b097;
}
.beWsfr_U:hover {
  background: #545555;
}
.active {
  background: #545555;
  color: #ddd;
}
.P9ZK1OTT,
.j88GOXPF {
  align-items: center;
  display: flex;
}
.P9ZK1OTT {
  margin-left: 10px;
}
.j88GOXPF {
  //background: linear-gradient(322deg, #1f6ff5 7.93%, #9a7ffc 92.22%);
  background-image: url('../../../assets/icon-assay.png');
  // border-radius: 4.615px;
  height: 36px;
  justify-content: center;
  width: 36px;
  background-size: cover;
}
.j88GOXPF-1 {
  background-image: url('../../../assets/icon-select.png');
}
.NvHLoWu8 {
  font-family: PingFang SC;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 20px;
  margin-left: 8px;
  text-align: justify;
  letter-spacing: 2px;
}

.nlux-comp-welcomeMessage-personaName {
  font-size: 30px;
  background: linear-gradient(270deg, #ff0033 3%, #3880f6 96%);
  color: transparent;
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  background-clip: text;
  font-weight: 600;
}
.nlux-comp-welcomeMessage-text {
  margin: 16px 0px 2px 0px;
  font-size: 15px;
  color: #ccc;
}
.nlux-comp-avatarPicture {
  background-image: url('../../../assets/AI.gif');
  width: 96px;
  height: 96px;
  background-size: cover;
}
</style>